export interface HistoryNode<T> {
    data: T,
    next: HistoryNode<T> | null,
    prev: HistoryNode<T> | null
}

export class HistoryLinkedList<T> {
    private head: HistoryNode<T> | null = null;
    private tail: HistoryNode<T> | null = null;
    private current: HistoryNode<T> | null = null;

    constructor(initialData:T) {
        this.head = this.createNode(initialData);
        this.tail = this.head;
        this.current = this.head;
    }

    private createNode(data:T):HistoryNode<T> {
        return {
            data,
            next: null,
            prev: null
        }
    }

    add(data:T) {
        const newNode = this.createNode(data);
        if (!this.current) return;

        if (this.current.next) {
            this.current.next.prev = null;
        }

        newNode.prev = this.current;
        this.current.next = newNode;
        this.current = newNode;
        this.tail = newNode;
    }

    forward(): HistoryNode<T> | null {
        if (this.current?.next) {
            this.current = this.current.next;
        }
        return this.current;
    }

    backward(): HistoryNode<T> | null {
        if (this.current?.prev) {
            this.current = this.current.prev;
        }
        return this.current;
    }

    getCurrent(): HistoryNode<T> | null {
        return this.current;
    }

    toHead(): HistoryNode<T> | null {
        this.current = this.head;
        return this.current;
    }

    toTail(): HistoryNode<T> | null {
        this.current = this.tail;
        return this.current;
    }

    clearNext() {
        if (this.current?.next) {
            this.current.next.prev = null;
            this.current.next = null;
            this.tail = this.current;
        }
    }

    canForward(): boolean {
        return !!this.current?.next;
    }

    canBackward(): boolean {
        return !!this.current?.prev;
    }
}